<?php

namespace app\api\controller\applets;

use Alipay\EasySDK\Kernel\Factory as alipayFactory;
use app\api\model\CarCate;
use app\api\model\MerchantCar;
use app\api\model\OrderChange;
use app\api\model\OrderContinue;
use app\api\model\OrderFace;
use app\api\model\User;
use app\common\controller\Api;
use app\common\model\PlatformLog;
use EasyWeChat\Factory;
use fast\Random;
use think\App;
use think\facade\Db;
use think\facade\Validate;
use think\facade\Config;
use app\common\library\Ems;
use app\common\library\Sms;
use think\facade\Log;
use think\Model;
use think\Request;

/**
 * 回调接口.
 */
class Notify
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';

    protected $model;
    protected $platform_model;
    /**
     * 构造方法
     * @access public
     * @param Request $request Request 对象
     */
    public function __construct(Request $request = null)
    {
        $this->model = new \app\api\model\Order();
        $this->platform_model = new PlatformLog();
    }

    /**
     * 微信预约下单回调.
     */
    public function orderNotify()
    {
        Log::write('预约下单微信支付回调逻辑开始'.date('Y-m-d H:i:s',time()));
        $config= Config::get('config_wechat.wechat_pay');
        $app = Factory::payment($config);
        $response = $app->handlePaidNotify(function ($message, $fail) use ($app) {
            Log::write($message);
            if ($message['return_code'] == "SUCCESS" && $message["result_code"] == "SUCCESS") {
                $out_trade_no = $message['out_trade_no'];//订单号
                $order = $this->model->where('out_trade_no', $out_trade_no)->find();
                //如果该订单未找到或已支付,返回true
                if (!$order || $order['status'] != 0) {
                    return true;
                }
                //更改订单状态
                $upda_data = [
                    'status'=> 1,
                    'transaction_id'=>$message['transaction_id'], //微信支付订单号
                    'time_end'=>strtotime($message['time_end']), //支付完成时间
                    'total_fee'=>$message['total_fee'] / 100, //支付金额
                ];
                $res = $this->model->where('out_trade_no', $out_trade_no)->update($upda_data);
                //平台流水
                $this->platform_model->save(['user_id' => $order['user_id'], 'amount' => $order['all_money'], 'type' => 1, 'log_note' => '预约下单支付', 'createtime' => time(), 'order_id' => $order['id'], 'order_type' => 1, 'total_order_id' => $order['id']]);
                //更改车辆状态
                MerchantCar::where('id', $order['merchant_car_id'])->update(['car_status' => 2]);
                //向商家发送短信
                $merchant_car = MerchantCar::where(['is_delete' => 1, 'id' => $order['merchant_car_id']])->find();
                $merchant_phone = \app\api\model\Merchant::where(['is_delete' => 1, 'id' => $order['merchant_id']])->value('merchant_phone');
                if($merchant_phone && $merchant_car){
                    $car_cate = CarCate::where('id', $merchant_car['type_id'])->value('cate_name');
                    $data = [
                        'numer' => $out_trade_no,
                        'model' => $car_cate,
                        'start_time' => date('Y-m-d H:i:s', $order['start_time']),
                        'end_time' => date('Y-m-d H:i:s', $order['end_time']),
                        'day' => $order['days'],
                        'pick_address' => $order['pick_address'],
                        'return_address' => $order['return_address'],
                    ];
                    $res = sendMsg($merchant_phone, $data, 'SMS_464116229');
                }
                //向用户发送短信
                $data = [
                    'time' => date('Y-m-d H:i:s', $order['start_time']),
                ];
                $res = sendMsg($order['user_phone'], $data, 'SMS_464101155');
                Log::write('预约下单微信支付回调逻辑结束'.date('Y-m-d H:i:s',time()));
                return true;
            }
        });
        return $response->send();
    }

    /**
     * 支付宝预约下单回调.
     */
    public function orderAlipayNotify(){
        Log::write('预约下单支付宝支付回调逻辑开始'.date('Y-m-d H:i:s',time()));
        // 请求数据处理
        $data = request()->post();
        Db::name('log')->insert(['content' => json_encode($data, JSON_UNESCAPED_UNICODE)]);
        $data = http_build_query($data);
        $data = explode('&', $data);
        $new_data = [];
        foreach ($data as $key=>$val){
            $rows = explode('=', $val);
            $new_data[$rows[0]] = urldecode($rows[1]);
        }
        if (!empty($new_data['fund_bill_list'])){
            $new_data['fund_bill_list'] = str_replace('&quot;', '"', $new_data['fund_bill_list']);
            $json = json_decode($new_data['fund_bill_list'], true);
            $new_data['fund_bill_list'] = json_encode($json);
        }
        // 才能去验证
        alipayFactory::setOptions(getOption());
        $result = alipayFactory::payment()->common()->verifyNotify($new_data);
        $out_trade_no = $new_data['out_trade_no'];//订单号
        $order = $this->model->where('out_trade_no', $out_trade_no)->find();
        //如果该订单未找到或已支付,返回true
        if (!$order || $order['status'] != 0) {
            return true;
        }
        //更改订单状态
        $upda_data = [
            'status'=> 1,
            'transaction_id'=>$new_data['trade_no'], //支付订单号
            'time_end'=>strtotime($new_data['gmt_payment']), //支付完成时间
            'total_fee'=>$new_data['total_amount'], //支付金额
        ];
        $res = $this->model->where('out_trade_no', $out_trade_no)->update($upda_data);
        //平台流水
        $this->platform_model->save(['user_id' => $order['user_id'], 'amount' => $order['all_money'], 'type' => 1, 'log_note' => '预约下单支付', 'createtime' => time(), 'order_id' => $order['id'], 'order_type' => 1, 'total_order_id' => $order['id']]);
        //更改车辆状态
        MerchantCar::where('id', $order['merchant_car_id'])->update(['car_status' => 2]);
//                //向商家发送短信
//                $merchant_phone = \app\api\model\Merchant::where(['is_delete' => 1, 'id' => $order['merchant_id'], 'status' => 1, 'examine_status' => 2])->value('merchant_phone');
//                if($merchant_phone){
//                    $res = sendMsg($merchant_phone, ['product' => '三峡畅行']);
//                }
        Log::write('预约下单支付宝支付回调逻辑结束'.date('Y-m-d H:i:s',time()));
    }

    /**
     * 微信续租支付回调.
     */
    public function continueWechatNotify()
    {
        Log::write('续租微信支付回调逻辑开始'.date('Y-m-d H:i:s',time()));
        $config= Config::get('config_wechat.wechat_pay');
        $app = Factory::payment($config);
        $response = $app->handlePaidNotify(function ($message, $fail) use ($app) {
            Log::write($message);
            if ($message['return_code'] == "SUCCESS" && $message["result_code"] == "SUCCESS") {
                $out_trade_no = $message['out_trade_no'];//订单号
                $order = OrderContinue::where('out_trade_no', $out_trade_no)->find()->toArray();
                //如果该订单未找到或已支付,返回true
                if (!$order || $order['pay_status'] != 1) {
                    return true;
                }
                //更改订单状态
                $upda_data = [
                    'pay_status'=> 2,
                    'transaction_id'=>$message['transaction_id'], //微信支付订单号
                    'time_end'=>strtotime($message['time_end']), //支付完成时间
                    'total_fee'=>$message['total_fee'] / 100, //支付金额
                ];
                $res = OrderContinue::where('out_trade_no', $out_trade_no)->update($upda_data);
                //更改主订单状态
                \app\api\model\Order::where('id', $order['order_id'])->update(['continue_status' => 4]);
                //平台流水
                $this->platform_model->save(['user_id' => $order['user_id'], 'amount' => $order['all_money'], 'type' => 8, 'log_note' => '续租支付', 'createtime' => time(), 'order_id' => $order['id'], 'order_type' => 1, 'total_order_id' => $order['order_id']]);
                //向商家发送短信
                $total_order = \app\api\model\Order::where('id', $order['order_id'])->find();//主订单
                if($total_order){
                    $merchant_car = MerchantCar::where(['is_delete' => 1, 'id' => $total_order['merchant_car_id']])->find();
                    $merchant_phone = \app\api\model\Merchant::where(['is_delete' => 1, 'id' => $total_order['merchant_id']])->value('merchant_phone');
                    if($merchant_phone && $merchant_car){
                        $car_cate = \app\api\model\CarCate::where('id', $merchant_car['type_id'])->value('cate_name');
                        $order_user = User::where('id', $order['user_id'])->find();
                        $data = [
                            'number' => $order['out_trade_no'],
                            'model' => $car_cate,
                            'car_number' => $order['car_number'],
                            'username' => $order_user['truename'],
                            'new_end_time' => date('Y-m-d H:i:s', $order['end_time']),
                            'end_time' => date('Y-m-d H:i:s', $total_order['end_time']),
                        ];
                        $last_end_time = OrderContinue::where(['is_delete' => 1, 'order_id' => $total_order['id'], 'continue_status' => 2])->where('pay_status', 'in', '1,2,4')->order('createtime', 'desc')->value('end_time');
                        if($last_end_time){
                            $data['end_time'] = date('Y-m-d H:i:s', $last_end_time);
                        }
                        $res = sendMsg($merchant_phone, $data, 'SMS_464111296');
                    }
                }
                Log::write('续租微信支付回调逻辑结束'.date('Y-m-d H:i:s',time()));
                return true;
            }
        });
        return $response->send();
    }

    /**
     * 支付宝续租支付回调.
     */
    public function continueAlipayNotify(){
        Log::write('续租支付宝支付回调逻辑开始'.date('Y-m-d H:i:s',time()));
        // 请求数据处理
        $data = request()->post();
        Db::name('log')->insert(['content' => json_encode($data, JSON_UNESCAPED_UNICODE)]);
        $data = http_build_query($data);
        $data = explode('&', $data);
        $new_data = [];
        foreach ($data as $key=>$val){
            $rows = explode('=', $val);
            $new_data[$rows[0]] = urldecode($rows[1]);
        }
        if (!empty($new_data['fund_bill_list'])){
            $new_data['fund_bill_list'] = str_replace('&quot;', '"', $new_data['fund_bill_list']);
            $json = json_decode($new_data['fund_bill_list'], true);
            $new_data['fund_bill_list'] = json_encode($json);
        }
        // 才能去验证
        alipayFactory::setOptions(getOption());
        $result = alipayFactory::payment()->common()->verifyNotify($new_data);
        $out_trade_no = $new_data['out_trade_no'];//订单号
        $order = OrderContinue::where('out_trade_no', $out_trade_no)->find()->toArray();
        //如果该订单未找到或已支付,返回true
        if (!$order || $order['pay_status'] != 1) {
            return true;
        }
        //更改订单状态
        $upda_data = [
            'pay_status'=> 2,
            'transaction_id'=>$new_data['trade_no'], //支付订单号
            'time_end'=>strtotime($new_data['gmt_payment']), //支付完成时间
            'total_fee'=>$new_data['total_amount'], //支付金额,
            'continue_status' => 4
        ];
        $res = OrderContinue::where('out_trade_no', $out_trade_no)->update($upda_data);
        //更改主订单状态
        \app\api\model\Order::where('id', $order['order_id'])->update(['continue_status' => 4]);
        //平台流水
        $this->platform_model->save(['user_id' => $order['user_id'], 'amount' => $order['all_money'], 'type' => 8, 'log_note' => '续租支付', 'createtime' => time(), 'order_id' => $order['id'], 'order_type' => 1, 'total_order_id' => $order['order_id']]);
        Log::write('续租支付宝支付回调逻辑结束'.date('Y-m-d H:i:s',time()));
    }

    /**
     * 微信换车支付回调.
     */
    public function changeWechatNotify()
    {
        Log::write('换车微信支付回调逻辑开始'.date('Y-m-d H:i:s',time()));
        $config= Config::get('config_wechat.wechat_pay');
        $app = Factory::payment($config);
        $response = $app->handlePaidNotify(function ($message, $fail) use ($app) {
            Log::write($message);
            if ($message['return_code'] == "SUCCESS" && $message["result_code"] == "SUCCESS") {
                $out_trade_no = $message['out_trade_no'];//订单号
                $order = OrderChange::where('out_trade_no', $out_trade_no)->find()->toArray();
                //如果该订单未找到或已支付,返回true
                if (!$order || $order['pay_status'] != 1) {
                    return true;
                }
                //更改订单状态
                $upda_data = [
                    'pay_status'=> 2,
                    'transaction_id'=>$message['transaction_id'], //微信支付订单号
                    'time_end'=>strtotime($message['time_end']), //支付完成时间
                    'total_fee'=>$message['total_fee'] / 100, //支付金额
                ];
                $res = OrderChange::where('out_trade_no', $out_trade_no)->update($upda_data);
                //更改主订单状态
                \app\api\model\Order::where('id', $order['order_id'])->update(['change_status' => 3]);
                //平台流水
                $this->platform_model->save(['user_id' => $order['user_id'], 'amount' => $order['diff_money'], 'type' => 6, 'log_note' => '换车支付', 'createtime' => time(), 'order_id' => $order['id'], 'order_type' => 1, 'total_order_id' => $order['order_id']]);
                Log::write('换车微信支付回调逻辑结束'.date('Y-m-d H:i:s',time()));
                return true;
            }
        });
        return $response->send();
    }

    /**
     * 支付宝换车支付回调.
     */
    public function changeAlipayNotify(){
        Log::write('换车支付宝支付回调逻辑开始'.date('Y-m-d H:i:s',time()));
        // 请求数据处理
        $data = request()->post();
        Db::name('log')->insert(['content' => json_encode($data, JSON_UNESCAPED_UNICODE)]);
        $data = http_build_query($data);
        $data = explode('&', $data);
        $new_data = [];
        foreach ($data as $key=>$val){
            $rows = explode('=', $val);
            $new_data[$rows[0]] = urldecode($rows[1]);
        }
        if (!empty($new_data['fund_bill_list'])){
            $new_data['fund_bill_list'] = str_replace('&quot;', '"', $new_data['fund_bill_list']);
            $json = json_decode($new_data['fund_bill_list'], true);
            $new_data['fund_bill_list'] = json_encode($json);
        }
        // 才能去验证
        alipayFactory::setOptions(getOption());
        $result = alipayFactory::payment()->common()->verifyNotify($new_data);
        $out_trade_no = $new_data['out_trade_no'];//订单号
        $order = OrderContinue::where('out_trade_no', $out_trade_no)->find()->toArray();
        //如果该订单未找到或已支付,返回true
        if (!$order || $order['pay_status'] != 1) {
            return true;
        }
        //更改订单状态
        $upda_data = [
            'pay_status'=> 2,
            'transaction_id'=>$new_data['trade_no'], //支付订单号
            'time_end'=>strtotime($new_data['gmt_payment']), //支付完成时间
            'total_fee'=>$new_data['total_amount'], //支付金额,
        ];
        $res = OrderChange::where('out_trade_no', $out_trade_no)->update($upda_data);
        //更改主订单状态
        \app\api\model\Order::where('id', $order['order_id'])->update(['change_status' => 3]);
        //平台流水
        $this->platform_model->save(['user_id' => $order['user_id'], 'amount' => $order['diff_money'], 'type' => 6, 'log_note' => '换车支付', 'createtime' => time(), 'order_id' => $order['id'], 'order_type' => 1, 'total_order_id' => $order['order_id']]);
        Log::write('换车支付宝支付回调逻辑结束'.date('Y-m-d H:i:s',time()));
    }

    /**
     * 微信当面付支付回调.
     */
    public function faceWechatNotify()
    {
        Log::write('当面付微信支付回调逻辑开始'.date('Y-m-d H:i:s',time()));
        $config= Config::get('config_wechat.wechat_pay');
        $app = Factory::payment($config);
        $response = $app->handlePaidNotify(function ($message, $fail) use ($app) {
            Log::write($message);
            if ($message['return_code'] == "SUCCESS" && $message["result_code"] == "SUCCESS") {
                $out_trade_no = $message['out_trade_no'];//订单号
                $order = OrderFace::where('out_trade_no', $out_trade_no)->find()->toArray();
                //如果该订单未找到或已支付,返回true
                if (!$order || $order['status'] != 1) {
                    return true;
                }
                //更改订单状态
                $upda_data = [
                    'status'=> 2,
                    'transaction_id'=>$message['transaction_id'], //微信支付订单号
                    'time_end'=>strtotime($message['time_end']), //支付完成时间
                    'total_fee'=>$message['total_fee'] / 100, //支付金额
                ];
                $res = OrderFace::where('out_trade_no', $out_trade_no)->update($upda_data);
                //更改主订单状态
                \app\api\model\Order::where('id', $order['order_id'])->update(['face_status' => 3]);
                //平台流水
                $this->platform_model->save(['user_id' => $order['user_id'], 'amount' => $order['all_money'], 'type' => 10, 'log_note' => '当面付支付', 'createtime' => time(), 'order_id' => $order['id'], 'order_type' => 1, 'total_order_id' => $order['order_id']]);
                Log::write('当面付微信支付回调逻辑结束'.date('Y-m-d H:i:s',time()));
                return true;
            }
        });
        return $response->send();
    }

    /**
     * 支付宝当面付支付回调.
     */
    public function faceAlipayNotify(){
        Log::write('换车支付宝支付回调逻辑开始'.date('Y-m-d H:i:s',time()));
        // 请求数据处理
        $data = request()->post();
        Db::name('log')->insert(['content' => json_encode($data, JSON_UNESCAPED_UNICODE)]);
        $data = http_build_query($data);
        $data = explode('&', $data);
        $new_data = [];
        foreach ($data as $key=>$val){
            $rows = explode('=', $val);
            $new_data[$rows[0]] = urldecode($rows[1]);
        }
        if (!empty($new_data['fund_bill_list'])){
            $new_data['fund_bill_list'] = str_replace('&quot;', '"', $new_data['fund_bill_list']);
            $json = json_decode($new_data['fund_bill_list'], true);
            $new_data['fund_bill_list'] = json_encode($json);
        }
        // 才能去验证
        alipayFactory::setOptions(getOption());
        $result = alipayFactory::payment()->common()->verifyNotify($new_data);
        $out_trade_no = $new_data['out_trade_no'];//订单号
        $order = OrderFace::where('out_trade_no', $out_trade_no)->find()->toArray();
        //如果该订单未找到或已支付,返回true
        if (!$order || $order['status'] != 1) {
            return true;
        }
        //更改订单状态
        $upda_data = [
            'status'=> 2,
            'transaction_id'=>$new_data['trade_no'], //支付订单号
            'time_end'=>strtotime($new_data['gmt_payment']), //支付完成时间
            'total_fee'=>$new_data['total_amount'], //支付金额,
        ];
        $res = OrderFace::where('out_trade_no', $out_trade_no)->update($upda_data);
        //更改主订单状态
        \app\api\model\Order::where('id', $order['order_id'])->update(['face_status' => 3]);
        //平台流水
        $this->platform_model->save(['user_id' => $order['user_id'], 'amount' => $order['all_money'], 'type' => 10, 'log_note' => '当面付支付', 'createtime' => time(), 'order_id' => $order['id'], 'order_type' => 1, 'total_order_id' => $order['order_id']]);
        Log::write('当面付支付宝支付回调逻辑结束'.date('Y-m-d H:i:s',time()));
    }
}
